<template>
	<view class="container">
		<view class="form-group">
			<label for="itemName">物品名称</label>
			<input v-model="form.itemName" class="input" focus />
		</view>
		<view class="form-group">
			<label for="itemPrice">物品价格</label>
			<input v-model="form.itemPrice" class="input" type="number" />
		</view>
		<view class="form-group">
			<label for="itemImage">上传图片</label>
			<uni-file-picker v-model="form.itemImage" fileMediatype="image" mode="grid" @select="select"
				@progress="progress" @success="success" @fail="fail" :limit="1"/>
		</view>
		<button type="button" class="submit-button" @click="onSubmit">提交</button>
	</view>
</template>

<script>
	export default {
		data() {

			return {
				form: {
					itemName: '',
					itemPrice: '',
					itemImages: {}
				},
			};
		},
		methods: {
			select(e) {
				console.log('选择文件：', e)
				this.form.itemImages = e.tempFilePaths;
			},
			// 获取上传进度
			progress(e) {
				console.log('上传进度：', e)
			},

			// 上传成功
			success(e) {
				console.log(e + "收拾收拾")
				this.form.itemImages = e.tempFiles;

			},

			// 上传失败
			fail(e) {
				console.log('上传失败：', e)
			},
			async onSubmit() {
				console.log(this.form)
				if (this.form.itemImages.length === 0) {
					uni.showToast({
						title: '请上传图片',
						icon: 'none'
					});
					return;
				}

				try {
					const res = await uni.uploadFile({
						url: 'http://localhost:3000/upload/file/save', // 替换为你的后端URL
						filePath: this.form.itemImages[0],
						name: 'file',
						formData: {
							businessId: this.$store.state.user.id,
							goodName: this.form.itemName,
							price: this.form.itemPrice
						},
						header: {
							'Content-Type': 'multipart/form-data'
						}
					});
					//0是数据
					if (res[1].statusCode === 201) { // 根据你的后端返回的状态码
						uni.showToast({
							title: '提交成功',
							icon: 'success',
							success() {
								// 2秒后执行跳转操作
								setTimeout(function() {
									// 这里执行你的跳转代码，比如页面跳转
									uni.navigateTo({
										url: '/pages/work/sell/index'
									});
								}, 2000);
								// this.$tab.switchTab("/pages/sell/index");
							}
						});
					} else {
						uni.showToast({
							title: '提交失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error(error);
					uni.showToast({
						title: '提交失败',
						icon: 'none'
					});
				}
			}
		}
	};
</script>

<style>
	.container {
		padding: 20px;
		background-color: white;
	}

	.form-group {
		margin-bottom: 20px;
	}

	label {
		display: block;
		margin-bottom: 12px;
		font-weight: bold;
		font-size: 18px;
	}

	.input {
		width: 100%;
		padding: 15px;
		font-size: 18px;
		border: 1px solid #ccc;
		border-radius: 4px;
		box-sizing: border-box;
	}

	.submit-button {
		width: 100%;
		padding: 18px;
		background-color: #007bff;
		color: #fff;
		border: none;
		border-radius: 4px;
		font-size: 20px;
		cursor: pointer;
		text-align: center;
		box-sizing: border-box;
	}

	.submit-button:hover {
		background-color: #0056b3;
	}
</style>